<template>
  <div class="char-box-im" :class="{readonly: isReadOnly}">
    <el-scrollbar ref="chatsScrollBar" wrap-class="message-scrollbar-wrapper" class="message-box">
      <div class="more-message text-center">
        <el-button :loading="loadingMore" @click.prevent="getMoreHistoryMessage" type="text">
          {{ historyFlagOver ? '没有更多的消息了' : '查看更多消息' }}
        </el-button>
      </div>
      <ul class="chats">

        <template v-for="(group, time) in chartsGroup">
          <li :key="time" class="time">{{ time }}</li>

          <li :key="index" v-for="(item, index) in group" :class="item.className">
            <img class="avatar" alt="头像" :src="getUserPhoto(getUserByKey(item.from))"/>
            <div class="message">
              <span class="arrow"> </span>
              <span class="body">
              <Aplayer
                v-if="item.objectURL && item.fileType == 'audio'"
                mini
                :music="{
                  src: item.objectURL
                }"
              ></Aplayer>

              <Viewer v-if="item.url && item.fileType == 'image'" :images="[item.url]">
                <img :src="item.url" width="300px"/>
              </Viewer>

              <span v-if="item.sourceMsg" v-html="item.sourceMsg"></span>
            </span>
            </div>
          </li>

        </template>
      </ul>
    </el-scrollbar>
    <div class="chat-bottom" v-if="!isReadOnly">
      <div class="grey-line"></div>
      <div class="tools-line">
        <label class="btn-file">
          <input :disabled="!canSendTo" v-if="fileTrigger" @change="sendImageMessage($event)" ref="imageInput"
                 type="file"
                 multiple="false">
          <i style="position: relative;" class="fa fa-image"></i>
        </label>
      </div>
      <div class="grey-line"></div>
      <div class="textarea-box">
        <textarea :disabled="!canSendTo" @keyup.enter="sendMessage" v-model="message" placeholder="请输入消息"
                  class="textarea"></textarea>
      </div>
      <div class="button">
        <span class="help-inline">Enter 发送, Ctrl+Enter 换行</span>
        <el-button :disabled="!canSendTo" type="primary" @click.prevent="sendMessage">发送</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import {Easemob} from '@/utils/Easemob'
import {alert, dotData} from '@/utils'
import L from 'lodash'
import {mapGetters, mapActions} from 'vuex'
import Aplayer from 'vue-aplayer'

export default {
  components: {
    Aplayer
  },
  data() {
    return {
      message: '',
      im: new Easemob(),
      fileTrigger: true,
      loadingMore: false
    }
  },
  computed: {
    sendTo() {
      return this.groupId
    },
    // 能发送
    canSendTo() {
      return !!this.sendTo
    },
    charts() {
      return this.GET_IM_CHART_DIALOG_GROUP_MESSAGE(this.sendTo)
    },
    chartsGroup() {
      return this.charts.reduce((total, item) => {
        if (Array.isArray(total[item.timeStr])) {
          total[item.timeStr].push(item)
        } else {
          total[item.timeStr] = [item]
        }
        return total
      }, {})
    },
    historyFlag() {
      if (this.sendTo) {
        return this.GET_IM_GROUP_MESSAGE_HISTORY(this.sendTo)
      }
      return {}
    },
    historyFlagOver() {
      return !!this.historyFlag.over
    },
    // 只读
    isReadOnly() {
      return this.IS_IM_READ_ONLY_GROUP_ID(this.sendTo)
    },
    ...mapGetters({
      imMembers: 'GET_IM_CHART_DIALOG_GROUP_MEMBERS_BY_WORKER',
      groupId: 'GET_IM_CHART_DIALOG_GROUP_ID',
      getOrderNoByGroup: 'GET_IM_CHART_DIALOG_GROUP_ID_ORDER_NO',
      GET_IM_CHART_EXT_MAP: 'GET_IM_CHART_EXT_MAP',
      GET_IM_CHART_DIALOG_GROUP_MESSAGE: 'GET_IM_CHART_DIALOG_GROUP_MESSAGE',
      GET_IM_CHART_DIALOG_UN_READ_LENGTH: 'GET_IM_CHART_DIALOG_UN_READ_LENGTH',
      GET_IM_CHART_DIALOG_LAST_MESSAGE: 'GET_IM_CHART_DIALOG_LAST_MESSAGE',
      GET_IM_GROUP_MESSAGE_HISTORY: 'GET_IM_GROUP_MESSAGE_HISTORY',
      GET_IM_CHART_DIALOG_MEMBER_E_NAME: 'GET_IM_CHART_DIALOG_MEMBER_E_NAME',
      currentWorker: 'GET_IM_CHART_CURRENT_WORKER',
      IS_IM_READ_ONLY_GROUP_ID: 'IS_IM_READ_ONLY_GROUP_ID'
    })
  },
  watch: {
    charts(val, oldVal) {
      if (this.loadingMore) {
        return
      }
      this.scrollToBottom()
    },
    sendTo: {
      handler(val, oldVal) {
        if (val === oldVal) {
          return
        }
        if (val) {
          this.getHistoryMessage()
        }
      },
      immediate: true
    }
  },
  methods: {
    // 发送im 文本消息
    sendMessage() {
      const message = L.trim(this.message)
      if (!message) {
        alert('请输入消息')
        return
      }
      if (!this.sendTo) {
        alert('发送对象必须')
        return
      }
      this.im.sendTextMessageGroup(message, this.sendTo, () => {
        this.message = ''
      })
    },
    // 发送图片消息
    sendImageMessage() {
      if (!this.sendTo) {
        alert('发送对象必须')
        return
      }
      this.im.sendGroupImageMessage(this.$refs.imageInput, this.sendTo, () => {
        this.fileTrigger = !this.fileTrigger
        this.$nextTick(_ => {
          this.fileTrigger = !this.fileTrigger
        })
      })
    },
    // 滚动到底
    scrollToBottom() {
      if (this.$refs['chatsScrollBar']) {
        this.$nextTick(_ => {
          const box = $(this.$refs['chatsScrollBar'].$el)
          let height = box.find('ul').height()
          const wrap = box.find('.el-scrollbar__wrap')
          wrap.animate({scrollTop: height}, 500)
        })
      }
    },
    // 获取历史消息
    getHistoryMessage(scroll = true) {
      if (!this.historyFlag.first) {
        this.im.getMessageLog(this.sendTo).then(_ => {
          this.SET_IM_GROUP_MESSAGE_HISTORY_FIRST({groupId: this.sendTo})
          if (scroll) {
            this.$nextTick(_ => {
              this.scrollToBottom()
            })
          }
        })
      }
    },
    // 获取更多历史消息
    getMoreHistoryMessage() {
      if (this.historyFlagOver) {
        return
      }
      this.loadingMore = true
      const msgId = dotData(this.charts, '[0].msgId')
      this.im.getMessageLog(this.sendTo, msgId).finally(_ => {
        this.loadingMore = false
      })
    },
    // 获取聊天用户头像
    getUserPhoto(item) {
      const avatar = dotData(item, 'userPhoto')
      if (avatar) {
        return `/api/ms-mongodb/file/download?fileId=${avatar}`
      } else {
        const userType = dotData(item, 'userType')
        if (userType === 'service') { //
          return '/static/images/im/kf-default.png'
        } else if (userType === 'merchant') {
          return '/static/images/im/sj.png'
        } else {
          return '/static/images/im/sj.png'
        }
      }
    },
    getUserByKey(eName, key) {
      const user = this.GET_IM_CHART_DIALOG_MEMBER_E_NAME(eName)
      if (key) {
        return dotData(user, key) || ''
      }
      return user
    },
    ...mapActions([
      'SET_IM_GROUP_MESSAGE_HISTORY_FIRST'
    ])
  }
}
</script>
